package cn.edu.sdjzu.cs.dingcan.servlet;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.edu.sdjzu.cs.dingcan.entity.Food;
import cn.edu.sdjzu.cs.dingcan.entity.FoodType;
import cn.edu.sdjzu.cs.dingcan.service.FoodService;
import cn.edu.sdjzu.cs.dingcan.service.FoodTypeService;
import cn.edu.sdjzu.cs.dingcan.utils.PageBean;
import org.apache.commons.lang3.StringUtils;

@WebServlet(name = "FoodServlet", urlPatterns = "/food")
public class FoodServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = -3439261320791952389L;
	// 创建service
	private final FoodService foodService = new FoodService();
	private final FoodTypeService foodTypeService = new FoodTypeService();

	@Override
	public void init(ServletConfig config) throws ServletException {

		super.init(config);
		// PageBean<Food> pageBean = new PageBean<>();
		// pageBean.setPageCount(6);
		// foodService.getAll(pageBean);
		// List<Food> list = foodService.getAll();
		// config.getServletContext().setAttribute("food", list);
		// config.getServletContext().setAttribute("pb", pageBean);

	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String method = request.getParameter("method");
		try {
			if ("add".equals(method)) {
				add(request, response);
			} else if ("list".equals(method)) {
				list(request, response);
			} else if ("show-edit".equals(method)) {
				showEdit(request, response);
			} else if ("update".equals(method)) {
				try {
					update(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else if ("delete".equals(method)) {
				delete(request, response);
			} else if ("search".equals(method)) {
				search(request, response);
			} else if ("findFoodType".equals(method)) {
				findFoodType(request, response);
				request.getRequestDispatcher("/sys/food/saveFood.jsp").forward(request, response);
			} else if ("query".equals(method)) {
				query(request, response);
			} else if ("getMenu".equals(method)) {
				getMenu(request, response);
			}
		} catch (SQLException ex) {
			response.sendError(HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED, "执行数据库操作时遇到SQL异常");
		}

	}

	private void getMenu(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	private void showEdit(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
		Long foodId = Long.parseLong(request.getParameter("food-id"));
		Food food = this.foodService.getById(foodId);
		List<FoodType> foodTypes = this.foodTypeService.findAll();
		request.setAttribute("food", food);
		request.setAttribute("foodTypes", foodTypes);
		request.getRequestDispatcher("/sys/food/updateFood.jsp").forward(request, response);
	}

	private void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		// 获取“当前页”参数； (第一次访问当前页为null)
		String currPage = StringUtils.defaultIfBlank(request.getParameter("currentPage"), "1");

		// 转换
		int currentPage = Integer.parseInt(currPage);

		// 创建PageBean对象，设置当前页参数； 传入service方法参数
		PageBean<Food> pageBean = new PageBean<>();
		pageBean.setCurrentPage(currentPage);

		// 调用service
		foodService.getAll(pageBean); // 【pageBean已经被dao填充了数据】
		// 保存pageBean对象，到request域中

		List<Food> list = pageBean.getPageData();

		request.setAttribute("pageBean", pageBean);
		request.setAttribute("list", list);
		request.getRequestDispatcher("/sys/food/foodList.jsp").forward(request, response);
	}

	private void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (ServletFileUpload.isMultipartContent(request)) {
			Food food = new Food();
			parseFoodFormDate(food, request);
			foodService.update(food);
		} else {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}
		list(request, response);
	}

	private void parseFoodFormDate(Food food, HttpServletRequest request) {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(10 * 1024 * 1024); 	// 单个文件大小限制
		upload.setSizeMax(50 * 1024 * 1024); 		// 总文件大小限制
		upload.setHeaderEncoding("UTF-8"); 			// 对中文文件编码处理

		String foodIdParam = request.getParameter("food-id");
		if(null != foodIdParam) {	// 修改时有food-id参数，添加时没有
			Long foodId = Long.parseLong(foodIdParam);
			food.setId(foodId);
		}
		List<FileItem> list = null;
		try {
			list = upload.parseRequest(request);
			for (FileItem item : list) {
				if (item.isFormField()) {		// 普通文本内容
					String name = item.getFieldName();
					// 获取值
					String value = item.getString();
					value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
					if("food-type-id".equals(name)) {
						FoodType foodType = new FoodType();
						foodType.setId(Long.parseLong(value));
						food.setFoodType(foodType);
					} else {
						BeanUtils.setProperty(food, name, value);
					}
				} else {// 上传内容
					String fieldName = item.getFieldName();
					String path = getServletContext().getRealPath("/upload");
					File f = new File(path);
					if (!f.exists()) {
						f.mkdir();
					}
					String name = item.getName();
					if (name != null && !"".equals(name.trim())) {
						BeanUtils.setProperty(food, fieldName,	("upload/" + name));
						//  拼接文件名
						File file = new File(path, name);
						//  上传
						if (!file.isDirectory()) {
							if(file.exists()) {    // 如存在同名文件，先删除
								file.delete();
							}
							item.write(file);
						}
						item.delete(); // 删除组件运行时产生的临时文件
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("菜品图片上传时遇到异常", e);
		}

	}
	public void findFoodType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<FoodType> foodtypes = foodTypeService.findAll();
		request.setAttribute("foodtypes", foodtypes);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		if (ServletFileUpload.isMultipartContent(request)) {
			Food food = new Food();
			parseFoodFormDate(food, request);
			try {
				foodService.add(food);
				list(request, response);
			} catch (SQLException throwables) {
				throw new RuntimeException("添加菜品时遇到数据库异常", throwables);
			}
		} else {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}
	}

	private void query(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			List<Food> list = foodService.getAll();
			request.setAttribute("list", list);

			// 获得食物类别的方法
			List<FoodType> types = new ArrayList<FoodType>();
			
			for (Food food : list) {
				FoodType foodtype = food.getFoodType();
				types.add(foodtype);
			}
			request.setAttribute("types", types);

			request.getRequestDispatcher("/sys/food/foodList.jsp").forward(request, response);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}

	private void search(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String keyword = request.getParameter("keyword");
			if (keyword != null) {
				List<Food> list = foodService.query(keyword);
				List<FoodType> types = new ArrayList<FoodType>();

				if (list != null) {
					for (Food food : list) {
						FoodType foodtype = food.getFoodType();
						types.add(foodtype);
					}
				}
				request.setAttribute("types", types);
				request.setAttribute("list", list);
				request.getRequestDispatcher("/sys/food/foodList.jsp").forward(request, response);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
		
	}

	private void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String id = request.getParameter("id");
			foodService.delete(Integer.parseInt(id));
			list(request, response);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);

	}

}
